package com.qdaily.ui.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import com.qdaily.supportlibrary.request.JsonData;
import com.qdaily.supportlibrary.util.NetUtil;
import com.qdaily.supportlibrary.util.QDJsonUtil;
import com.qdaily.ui.QDBaseActivity;
import com.qdaily.ui.R;
import com.qdaily.ui.data.Constants;
import com.qdaily.ui.data.UserInformation;
import com.qdaily.ui.net.NetConfigs;
import com.qdaily.ui.net.entity.UserCenterEntity;
import com.qdaily.ui.util.BusProvider;
import com.qdaily.ui.util.QDUtil;

import java.util.HashMap;

/**
 * 账户登录
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/13/15
 * Time: 16:58
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class LoginActivity extends QDBaseActivity implements View.OnClickListener,
        PlatformActionListener {

    private ImageView imageViewLoginSina;
    private ImageView imageViewLoginQQ;
    private ImageView imageViewLoginWX;
    private LinearLayout linearLayoutLoginClose;
    private android.widget.EditText editTextEditLoginEmail;
    private android.widget.EditText editTextLoginPassword;
    private ImageView imageViewLoginPwdVisiable;
    private TextView textViewLoginLogin;
    private TextView textViewLoginCancel;
    private TextView textViewLoginForgetPwd;
    private TextView textViewLoginNewAccount;

    //是否显示密码
    private boolean mPwdDisplayFlg = false;

    //third party
    private static final int MSG_AUTH_CANCEL = 1;
    private static final int MSG_AUTH_ERROR = 2;
    private static final int MSG_AUTH_COMPLETE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initViewRes();
    }

    private void initViewRes() {
        this.textViewLoginNewAccount = (TextView) findViewById(R.id.textViewLoginNewAccount);
        this.textViewLoginForgetPwd = (TextView) findViewById(R.id.textViewLoginForgetPwd);
        this.textViewLoginCancel = (TextView) findViewById(R.id.textViewLoginCancel);
        this.textViewLoginLogin = (TextView) findViewById(R.id.textViewLoginLogin);
        this.imageViewLoginPwdVisiable = (ImageView) findViewById(R.id.imageViewLoginPwdVisiable);
        this.editTextLoginPassword = (EditText) findViewById(R.id.editTextLoginPassword);
        this.editTextEditLoginEmail = (EditText) findViewById(R.id.editTextEditLoginEmail);
        this.imageViewLoginWX = (ImageView) findViewById(R.id.imageViewLoginWX);
        this.imageViewLoginQQ = (ImageView) findViewById(R.id.imageViewLoginQQ);
        this.imageViewLoginSina = (ImageView) findViewById(R.id.imageViewLoginSina);
        this.linearLayoutLoginClose = (LinearLayout) findViewById(R.id.linearLayoutLoginClose);

        this.linearLayoutLoginClose.setOnClickListener(this);
        this.textViewLoginNewAccount.setOnClickListener(this);
        this.textViewLoginForgetPwd.setOnClickListener(this);
        this.imageViewLoginSina.setOnClickListener(this);
        this.imageViewLoginQQ.setOnClickListener(this);
        this.imageViewLoginWX.setOnClickListener(this);
        this.imageViewLoginPwdVisiable.setOnClickListener(this);
        this.textViewLoginLogin.setOnClickListener(this);
        this.textViewLoginCancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.imageViewLoginSina:
                authorize(SinaWeibo.NAME);
                break;
            case R.id.imageViewLoginQQ:
                authorize(QQ.NAME);
                break;
            case R.id.imageViewLoginWX:
                authorize(Wechat.NAME);
                break;
            case R.id.imageViewLoginPwdVisiable:
                isPasswordVisiable();
                break;
            case R.id.textViewLoginLogin:
                iWantLogin();
                break;
            case R.id.textViewLoginCancel:
                this.finish();
                break;
            case R.id.textViewLoginNewAccount:
                iWantRegister();
                break;
            case R.id.textViewLoginForgetPwd:
                iWantForgetPwd();
                break;
            case R.id.linearLayoutLoginClose:
                finish();
                break;
        }
    }

    // third party login
    private void authorize(String platfromName) {
        Platform platform = ShareSDK.getPlatform(this, platfromName);
        platform.setPlatformActionListener(this);
        platform.showUser(platfromName);
    }

    private void iWantForgetPwd() {
        Intent retrievePasswordIntent = new Intent(this, RetrievePasswordActivity.class);
        startActivity(retrievePasswordIntent);
    }

    private void iWantRegister() {
        Intent registerIntent = new Intent(this, RegisterActivity.class);
        startActivity(registerIntent);
    }

    private void isPasswordVisiable() {
        if (!mPwdDisplayFlg) {
            editTextLoginPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            editTextLoginPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }
        mPwdDisplayFlg = !mPwdDisplayFlg;
        editTextLoginPassword.postInvalidate();
        CharSequence text = editTextLoginPassword.getText();
        Spannable spanText = (Spannable) text;
        Selection.setSelection(spanText, text.length());
        imageViewLoginPwdVisiable.setSelected(mPwdDisplayFlg);
    }

    private void iWantLogin() {
        String email = editTextEditLoginEmail.getText().toString();
        if (TextUtils.isEmpty(email)) {
            displayToast(R.string.please_entry_email);
            return;
        }
        if (!QDUtil.isEmail(email)) {
            displayToast(R.string.entry_email_is_wrong);
            return;
        }
        String password = editTextLoginPassword.getText().toString();
        if (TextUtils.isEmpty(password)) {
            displayToast(R.string.please_entry_password);
            return;
        }
        if (password.length() < 8) {
            displayToast(R.string.entry_password_is_wrong);
            return;
        }
        getRequestManager().requestSignin(email, password);
    }

    @Override
    protected void onRequestCallBack(NetUtil.NetParams params, JsonData response) {
        super.onRequestCallBack(params, response);
        if (params instanceof NetConfigs.RequestSignin || params instanceof NetConfigs.RequestSocialAction) {
            //parse
            UserCenterEntity userCenterEntity = QDJsonUtil.Json2Object(response.toString(), UserCenterEntity.class);
            if (null != userCenterEntity.getResponse() && userCenterEntity.getMeta().getStatus() == NetConfigs.HTTP_RESPONSE_200) {
                //这里我考虑的是，服务器返回的模板，我翻译成本地的保存到json里。全局使用。
                UserInformation userInformation = new UserInformation().translation(userCenterEntity);
                String userInformationJson = QDJsonUtil.getJsonString(userInformation);
                boolean isSaveCompleted = getUserInformationManager().updateUserInformation(userInformationJson);
                if (isSaveCompleted) {
                    //更新cookie
                    NetConfigs.getCookie(getUserInformationManager().getUserInformation().getCookie());
                    //更新主页
                    BusProvider.getInstance().post(userInformation);
                    this.finish();
                }
            } else {
                displayToast(userCenterEntity.getMeta().getMsg());
            }
        }
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
        final String socialToken = platform.getDb().getToken();
        final String socialUid = platform.getDb().getUserId();
        final String socialUserName = platform.getDb().getUserName();
        final String socialUserIcon = platform.getDb().getUserIcon();
        final int socialType = Constants.SocialType.getSocialType(platform.getName());

        getRequestManager().requestSocialAction(
                socialUid,
                socialToken,
                socialUserName,
                socialUserIcon,
                socialType);
    }

    @Override
    public void onError(Platform platform, int action, Throwable throwable) {
        if (action == Platform.ACTION_USER_INFOR) {
            thirdParty.sendEmptyMessage(MSG_AUTH_ERROR);
        }
        throwable.printStackTrace();
    }

    @Override
    public void onCancel(Platform platform, int action) {
        if (action == Platform.ACTION_USER_INFOR) {
            thirdParty.sendEmptyMessage(MSG_AUTH_CANCEL);
        }
    }

    private Handler thirdParty = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_AUTH_CANCEL: {
                    //取消授权
                    displayToast(R.string.auth_cancel);
                }
                break;
                case MSG_AUTH_ERROR: {
                    //授权错误
                    displayToast(R.string.auth_error);
                }
                break;
            }
        }
    };
}
